<template>
  <div class="employee-container">
    <!-- 查询表单 -->
    <div class="search-form">
      <el-form :model="formData" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="员工姓名">
              <el-input v-model="formData.empName" placeholder="请输入员工姓名" clearable @keyup.enter="onQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门">
              <el-select v-model="formData.deptId" placeholder="请选择部门" clearable filterable>
                <el-option v-for="item in deptList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-button type="primary" @click="onQuery">查询</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="success" @click="onAdd">新增</el-button>
            <el-button type="danger" @click="onDelete">批量删除</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 员工表格 -->
    <div class="employee-table">
      <el-table :data="nodeList" border @selection-change="handleSelectionChange">
        <el-table-column fixed="left" type="selection" width="50" align="center" />
        <el-table-column prop="empId" align="center" label="员工编号" width="150" fixed />
        <el-table-column prop="name" align="center" label="员工姓名" width="100" />
        <el-table-column prop="sex" align="center" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.sex == 1 ? "男" : "女" }}
          </template>
        </el-table-column>
        <el-table-column prop="age" align="center" label="年龄" width="80" />
        <el-table-column prop="ethnicity" align="center" label="民族" width="80" />
        <el-table-column prop="idNumber" align="center" label="身份证号" width="180" />
        <el-table-column prop="birth" align="center" label="出生日期" width="120" />
        <el-table-column prop="nationality" align="center" label="籍贯" width="130" />
        <el-table-column prop="political" align="center" label="政治面貌" width="120">
          <template #default="scope">
            <div v-if="scope.row.political === 0">群众</div>
            <div v-else-if="scope.row.political === 1">共青团员</div>
            <div v-else-if="scope.row.political === 2">中共党员</div>
            <div v-else-if="scope.row.political === 3">其他</div>
          </template>
        </el-table-column>
        <el-table-column prop="maritalStatus" align="center" label="婚姻状况" width="100">
          <template #default="scope">
            {{ scope.row.maritalStatus == 0 ? "未婚" : "已婚" }}
          </template>
        </el-table-column>
        <el-table-column prop="highestEducation" align="center" label="学历" width="100">
          <template #default="scope">
            <div v-if="scope.row.highestEducation === 0">小学</div>
            <div v-else-if="scope.row.highestEducation === 1">初中</div>
            <div v-else-if="scope.row.highestEducation === 2">高中</div>
            <div v-else-if="scope.row.highestEducation === 3">大专</div>
            <div v-else-if="scope.row.highestEducation === 4">本科</div>
            <div v-else-if="scope.row.highestEducation === 5">硕士</div>
            <div v-else-if="scope.row.highestEducation === 6">博士</div>
            <div v-else-if="scope.row.highestEducation === 7">其他</div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" align="center" label="联系电话" width="120" />
        <el-table-column prop="email" align="center" label="邮箱" width="180" />
        <el-table-column prop="address" align="center" label="所属地区" width="150" />
        <el-table-column prop="detailedAddress" align="center" label="家庭详细住址" width="200" />
        <el-table-column prop="empForm" align="center" label="聘用形式" width="100" />
        <el-table-column prop="entryDate" align="center" label="入职日期" width="120" />
        <el-table-column prop="regularizationDate" align="center" label="转正日期" width="120" />
        <el-table-column prop="contractStartDate" align="center" label="合同起始日期" width="120" />
        <el-table-column prop="contractDuration" align="center" label="合同年限" width="100" />
        <el-table-column prop="contractEndDate" align="center" label="合同截止日期" width="120" />
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="editNode(scope.row)">编辑</el-button>
            <el-button link type="warning" size="small"
              @click="resetPassword(scope.row.empId, scope.row.name)">重置密码</el-button>
            <el-button link type="danger" size="small" @click="del(scope.row.empId, scope.row.name)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination :current-page="page.currentPage" :page-size="page.pageSize" :total="page.total"
        layout="total, prev, pager, next, jumper" @current-change="handlerCurrentPage" />
    </div>

    <!-- 新建员工信息框 -->
    <el-dialog v-model="addEmpDialogFormVisible" @close="initAddForm" title="添加员工" width="800" align-center>
      <el-form :model="addData" class="demo-form" label-position="right" label-width="100px">
        <div class="form-row">
          <el-form-item label="员工姓名" required>
            <el-input v-model="addData.name" placeholder="请输入员工姓名"></el-input>
          </el-form-item>
          <el-form-item label="部门" required>
            <el-select v-model="addDeptData.deptId" placeholder="请选择部门" clearable>
              <el-option v-for="item in deptList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="出生日期">
            <el-date-picker v-model="addData.birth" type="date" placeholder="输入身份证号获取出生日期" disabled />
          </el-form-item>
          <el-form-item label="性别" required>
            <el-select v-model="addData.sex" placeholder="请选择性别" clearable>
              <el-option label="女" value="0" />
              <el-option label="男" value="1" />
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="联系电话" required>
            <el-input v-model="addData.phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" required>
            <el-input v-model="addData.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="身份证号" required>
            <el-input v-model="addData.idNumber" placeholder="请输入身份证号" @blur="handleIdCardInput"></el-input>
          </el-form-item>
          <el-form-item label="民族">
            <el-input v-model="addData.ethnicity" placeholder="请输入民族"></el-input>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="最高学历" required>
            <el-select v-model="addData.highestEducation" placeholder="请选择学历" clearable>
              <el-option label="小学" value="0" />
              <el-option label="初中" value="1" />
              <el-option label="高中" value="2" />
              <el-option label="大专" value="3" />
              <el-option label="本科" value="4" />
              <el-option label="硕士" value="5" />
              <el-option label="博士" value="6" />
              <el-option label="其他" value="7" />
            </el-select>
          </el-form-item>
          <el-form-item label="籍贯" required>
            <el-cascader v-model="nationalityList" :options="regionData" placeholder="请选择籍贯所在地" clearable
              @change="formatNationality" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="政治面貌" required>
            <el-select v-model="addData.political" placeholder="请选择政治面貌" clearable>
              <el-option label="群众" value="0" />
              <el-option label="共青团员" value="1" />
              <el-option label="中共党员" value="2" />
              <el-option label="其他" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="婚姻状况" required>
            <el-select v-model="addData.maritalStatus" placeholder="请选择婚姻状况" clearable>
              <el-option label="已婚" value="1" />
              <el-option label="未婚" value="0" />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="所属地区" label-width="100px" required>
            <el-cascader v-model="addressList" :options="regionData" placeholder="请选择目前居住地区" clearable
              @change="formatAddress" />
          </el-form-item>
          <el-form-item label="详细地址" label-width="100px" required>
            <el-input v-model="addData.detailedAddress" placeholder="请输入详细家庭地址"></el-input>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="入职日期" label-width="100px">
            <el-date-picker v-model="addData.entryDate" type="date" placeholder="选择入职日期" @change="formatEntryDate" />
          </el-form-item>
          <el-form-item label="转正日期" label-width="100px">
            <el-date-picker v-model="addData.regularizationDate" type="date" placeholder="选择转正日期"
              @change="formatRegularizationDate" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="合同起始日期" label-width="100px">
            <el-date-picker v-model="addData.contractStartDate" type="date" placeholder="选择合同起始日期"
              @change="formatContractStartDate" />
          </el-form-item>
          <el-form-item label="合同终止日期" label-width="100px">
            <el-date-picker v-model="addData.contractEndDate" type="date" placeholder="选择合同终止日期"
              @change="formatContractEndDate" />
          </el-form-item>
        </div>

        <el-form-item label="聘用形式" label-width="100px">
          <el-select v-model="addData.empForm" placeholder="请选择聘用形式" clearable>
            <el-option label="正式员工" value="正式" />
            <el-option label="实习生" value="实习" />
            <el-option label="劳务派遣" value="劳务" />
            <el-option label="外包员工" value="外包" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addEmpDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 员工信息编辑框 -->
    <el-dialog v-model="editEmpDialogFormVisible" @close="initEditForm" title="修改员工信息" width="800" align-center>
      <el-form :model="editData" class="demo-form" label-position="right" label-width="100px">
        <div class="form-row">
          <el-form-item label="员工编号" label-width="100px">
            <el-input v-model="editData.empId" disabled></el-input>
          </el-form-item>
          <el-form-item label="性别" label-width="100px" required>
            <el-select v-model="editSex" placeholder="请选择性别" clearable @change="updateSex">
              <el-option label="女" value="0" />
              <el-option label="男" value="1" />
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="员工姓名" label-width="100px" required>
            <el-input v-model="editData.name" placeholder="请输入员工姓名"></el-input>
          </el-form-item>
          <el-form-item label="民族" label-width="100px">
            <el-input v-model="editData.ethnicity" placeholder="请输入民族"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="出生日期" label-width="100px">
            <el-date-picker v-model="editData.birth" type="date" placeholder="你的出生日期" disabled/>
          </el-form-item>
          <el-form-item label="年龄" label-width="100px">
            <el-input v-model="editData.age" placeholder="你的年龄" disabled></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="身份证号" label-width="100px" required>
            <el-input v-model="editData.idNumber" placeholder="请输入身份证号" @blur="updateIdCardInput"></el-input>
          </el-form-item>
          <el-form-item label="籍贯" label-width="100px" required>
            <el-cascader v-model="editNationalityList" :options="regionData" placeholder="请选择籍贯所在地" clearable
              @change="formatEditNationality" />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="联系电话" label-width="100px" required>
            <el-input v-model="editData.phone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" label-width="100px" required>
            <el-input v-model="editData.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="政治面貌" label-width="100px" required>
            <el-select v-model="editPolitical" placeholder="请选择政治面貌" clearable @change="updatePolitical">
              <el-option label="群众" value="0" />
              <el-option label="共青团员" value="1" />
              <el-option label="中共党员" value="2" />
              <el-option label="其他" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="婚姻状况" label-width="100px" required>
            <el-select v-model="editMaritalStatus" placeholder="请选择婚姻状况" clearable @change="updateMaritalStatus">
              <el-option label="已婚" value="1" />
              <el-option label="未婚" value="0" />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="所属地区" label-width="100px" required>
            <el-cascader v-model="editAddressList" :options="regionData" placeholder="请选择目前居住地区" clearable
              @change="formatEditAddress" />
          </el-form-item>
          <el-form-item label="详细地址" label-width="100px" required>
            <el-input v-model="editData.detailedAddress" placeholder="请输入详细家庭地址"></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="入职日期" label-width="100px">
            <el-date-picker v-model="editData.entryDate" type="date" placeholder="选择入职日期"
              @change="formatEditEntryDate" />
          </el-form-item>
          <el-form-item label="转正日期" label-width="100px">
            <el-date-picker v-model="editData.regularizationDate" type="date" placeholder="选择转正日期"
              @change="formatEditRegularizationDate" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="聘用形式" label-width="100px">
            <el-select v-model="editData.empForm" placeholder="请选择聘用形式" clearable>
              <el-option label="正式员工" value="正式" />
              <el-option label="实习生" value="实习" />
              <el-option label="劳务派遣" value="劳务" />
              <el-option label="外包员工" value="外包" />
            </el-select>
          </el-form-item>
          <el-form-item label="合同年限" label-width="100px">
            <el-input v-model="editData.contractDuration" placeholder="合同年限" disabled></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="合同起始日期" label-width="100px">
            <el-date-picker v-model="editData.contractStartDate" type="date" placeholder="选择合同起始日期"
              @change="formatEditContractStartDate" />
          </el-form-item>
          <el-form-item label="合同终止日期" label-width="100px">
            <el-date-picker v-model="editData.contractEndDate" type="date" placeholder="选择合同终止日期"
              @change="formatEditContractEndDate" />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="最高学历" label-width="100px" required>
            <el-select v-model="editHighestEducation" placeholder="请选择学历" clearable @change="updateHighestEducation">
              <el-option label="小学" value="0" />
              <el-option label="初中" value="1" />
              <el-option label="高中" value="2" />
              <el-option label="大专" value="3" />
              <el-option label="本科" value="4" />
              <el-option label="硕士" value="5" />
              <el-option label="博士" value="6" />
              <el-option label="其他" value="7" />
            </el-select>
          </el-form-item>
        </div>

      </el-form>
      <template #footer>
        <el-button @click="editEmpDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { regionData } from "element-china-area-data";
import { addEmployeeAndDepartment, getEmployeeList, updateEmployee } from "../../api/basedata";
import { ElMessageBox, ElMessage } from 'element-plus';
import { deleteEmployee } from "../../api/basedata";
import { deleteBatchEmployee } from "../../api/basedata";
import { resetEmployeePassword } from "../../api/basedata";
import { getAllDepts } from "../../api/dept";
export default {
  data() {
    return {
      addEmpDialogFormVisible: false,
      editEmpDialogFormVisible: false,
      formData: {
        empName: "",
        deptId: "",
        pageNum: "",
        pageSize: ""
      },
      addData: {
        empId: "",
        name: "",
        birth: "",
        age: "",
        sex: "",
        idNumber: "",
        ethnicity: "",
        political: "",
        nationality: "",
        address: "",
        maritalStatus: "",
        detailedAddress: "",
        phone: "",
        email: "",
        highestEducation: "",
        entryDate: "",
        regularizationDate: "",
        password: "",
        contractStartDate: "",
        contractEndDate: "",
        contractDuration: "",
        empForm: ""
      },
      addDeptData: {
        deptId: "",
        empId: "",
      },
      editData: {
        name: "",
        empId: "",
        sex: "",
        birth: "",
        age: "",
        ethnicity: "",
        idNumber: "",
        phone: "",
        email: "",
        nationality: "",
        address: "",
        detailedAddress: "",
        political: "",
        maritalStatus: "",
        highestEducation: "",
        entryDate: "",
        contractStartDate: "",
        contractEndDate: "",
        contractDuration: "",
      },
      page: {
        currentPage: 1,
        pageSize: 8,
        total: 0,
      },
      regionData,
      nodeList: [],
      addressList: [],
      nationalityList: [],
      editAddressList: [],
      editNationalityList: [],
      delEmpId: [],
      editSex: "",
      editPolitical: "",
      editMaritalStatus: "",
      editHighestEducation: "",
      deptList: []
    };
  },
  mounted() {
    this.getList();
    this.getDepts();
    
  },
  methods: {
    //提交查询数据
    onQuery() {
      this.getList();
    },
    //重置查询数据
    onReset() {
      this.formData.empName = "";
      this.formData.deptId = "";
    },
    //新增员工
    onAdd() {
      this.addEmpDialogFormVisible = true;
    },
    // 格式化日期为 yyyy-MM-dd
    formatDate(date) {
      if (!date) return "";
      const formatter = new Intl.DateTimeFormat("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
      });
      const parts = formatter.formatToParts(date);
      const year = parts.find(part => part.type === "year").value;
      const month = parts.find(part => part.type === "month").value;
      const day = parts.find(part => part.type === "day").value;
      return `${year}-${month}-${day}`;
    },
    // 格式化出生日期
    formatBirthDate() {
      if (this.addData.birth) {
        this.addData.birth = this.formatDate(new Date(this.addData.birth));
        this.calculateAge();
      }
    },

    // 格式化入职日期
    formatEntryDate() {
      if (this.addData.entryDate) {
        this.addData.entryDate = this.formatDate(new Date(this.addData.entryDate));
      }
    },

    // 格式化转正日期
    formatRegularizationDate() {
      if (this.addData.regularizationDate) {
        this.addData.regularizationDate = this.formatDate(new Date(this.addData.regularizationDate));
        // 如果需要根据转正日期计算其他信息，可以在这里调用
      }
    },

    // 格式化合同起始日期
    formatContractStartDate() {
      if (this.addData.contractStartDate) {
        this.addData.contractStartDate = this.formatDate(new Date(this.addData.contractStartDate));
        this.calculateContractDuration();
      }
    },

    // 格式化合同终止日期
    formatContractEndDate() {
      if (this.addData.contractEndDate) {
        this.addData.contractEndDate = this.formatDate(new Date(this.addData.contractEndDate));
        this.calculateContractDuration();
      }
    },

    //根据身份证号生成出生日期
    handleIdCardInput() {
      // 验证身份证格式
      if (!/(^\d{15}$)|(^\d{17}[\dXx]$)/.test(this.addData.idNumber)) {
        this.$message.warning('身份证号格式不正确，请输入15位或18位身份证号');
        return;
      }
      // 提取出生日期
      let birthday = '';
      if (this.addData.idNumber.length === 15) {
        // 15位身份证：19 + 年(7-8位) + 月(9-10) + 日(11-12)
        birthday = `19${this.addData.idNumber.substr(6, 2)}-${this.addData.idNumber.substr(8, 2)}-${this.addData.idNumber.substr(10, 2)}`;
      } else if (this.addData.idNumber.length === 18) {
        // 18位身份证：年(7-10) + 月(11-12) + 日(13-14)
        birthday = `${this.addData.idNumber.substr(6, 4)}-${this.addData.idNumber.substr(10, 2)}-${this.addData.idNumber.substr(12, 2)}`;
      }
      // 填充到出生日期字段
      this.addData.birth = birthday;
      this.formatBirthDate(); // 格式化出生日期
      this.calculateAge();
    },
    //根据身份证号更新出生日期
    updateIdCardInput() {
      // 验证身份证格式
      if (!/(^\d{15}$)|(^\d{17}[\dXx]$)/.test(this.editData.idNumber)) {
        this.$message.warning('身份证号格式不正确，请输入15位或18位身份证号');
        return;
      }
      // 提取出生日期
      let birthday = '';
      if (this.editData.idNumber.length === 15) {
        // 15位身份证：19 + 年(7-8位) + 月(9-10) + 日(11-12)
        birthday = `19${this.editData.idNumber.substr(6, 2)}-${this.editData.idNumber.substr(8, 2)}-${this.editData.idNumber.substr(10, 2)}`;
      } else if (this.editData.idNumber.length === 18) {
        // 18位身份证：年(7-10) + 月(11-12) + 日(13-14)
        birthday = `${this.editData.idNumber.substr(6, 4)}-${this.editData.idNumber.substr(10, 2)}-${this.editData.idNumber.substr(12, 2)}`;
      }
      // 填充到出生日期字段
      this.editData.birth = birthday;
      this.formatEditBirthDate(); // 格式化出生日期
      this.calculateEditAge();
    },
    // 计算年龄
    calculateAge() {
      if (!this.addData.birth) return;
      const birthDate = new Date(this.addData.birth);
      const today = new Date();
      // 计算年份差
      let age = today.getFullYear() - birthDate.getFullYear();
      // 计算月份差
      const monthDiff = today.getMonth() - birthDate.getMonth();
      // 如果当前月份小于出生月份，或者月份相同但日期未到生日，年龄减1
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }
      this.addData.age = age;
    },

    // 计算合同年限
    calculateContractDuration() {
      if(!this.addData.contractStartDate || !this.addData.contractEndDate) 
        this.addData.contractDuration = 0;
      if (this.addData.contractStartDate && this.addData.contractEndDate) {
        const startDate = new Date(this.addData.contractStartDate);
        const endDate = new Date(this.addData.contractEndDate);
        const duration = (endDate - startDate) / (1000 * 60 * 60 * 24 * 365);
        this.addData.contractDuration = Math.round(duration);
      }
    },

    // 格式化籍贯
    formatNationality() {
      if (this.nationalityList && this.nationalityList.length === 3) {
        const [provinceCode, cityCode, districtCode] = this.nationalityList;
        const province = this.findAreaName(provinceCode);
        const city = this.findAreaName(cityCode);
        const district = this.findAreaName(districtCode);
        this.addData.nationality = `${province}/${city}/${district}`;
      }
    },

    // 格式化地址
    formatAddress() {
      if (this.addressList && this.addressList.length === 3) {
        const [provinceCode, cityCode, districtCode] = this.addressList;
        const province = this.findAreaName(provinceCode);
        const city = this.findAreaName(cityCode);
        const district = this.findAreaName(districtCode);
        this.addData.address = `${province}/${city}/${district}`;
      }
    },

    // 查找地区名称
    findAreaName(code) {
      const area = this.findAreaByCode(code);
      return area ? area.label : "";
    },

    // 递归查找地区
    findAreaByCode(code, options = this.regionData) {
      for (const option of options) {
        if (option.value === code) {
          return option;
        }
        if (option.children) {
          const result = this.findAreaByCode(code, option.children);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },

    // 生成员工编号
    generateEmployeeId() {
      const randomString = Math.random().toString(36).substring(2, 12);
      this.addData.empId = `user_${randomString}`;
      this.addDeptData.empId = this.addData.empId;
    },
    // 初始化表单
    initAddForm() {
      this.addData = {
        empName: "",
        birth: "",
        age: "",
        sex: "",
        idNumber: "",
        ethnicity: "",
        political: "",
        nationality: "",
        address: "",
        maritalStatus: "",
        detailedAddress: "",
        phone: "",
        email: "",
        highestEducation: "",
        entryDate: "",
        regularizationDate: "",
        contractStartDate: "",
        contractEndDate: "",
        contractDuration: "",
        empId: "",
        empForm: "",
        password: "",
      };
      this.addDeptData = {
        deptId: "",
        empId: "",
      };
      this.addressList = [];
      this.nationalityList = [];
    },
    // 提交表单
    submitForm() {
      if (!this.addData.name) {
        this.$message.error('请输入员工姓名');
        return;
      }
      if (!this.addDeptData.deptId) {
        this.$message.error('请选择部门');
        return;
      }
      //性别验证
      if (this.addData.sex===undefined) {
        this.$message.error('请选择性别');
        return;
      }
      // 电话号码验证
      if (!this.addData.phone) {
        this.$message.error('请输入联系电话');
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(this.addData.phone)) {
        this.$message.error('请输入正确的11位手机号码');
        return;
      }
      // 籍贯验证
      if (!this.nationalityList || this.nationalityList.length < 3) {
        this.$message.error('请选择籍贯所在地');
        return;
      }
      //学历验证
      if (this.addData.highestEducation===undefined) {
        this.$message.error('请选择最高学历');
        return;
      }
      //政治面貌验证
      if (!this.addData.political===undefined) {
        this.$message.error('请选择政治面貌');
        return;
      }
      //婚姻状况验证
      if (!this.addData.maritalStatus===undefined) {
        this.$message.error('请选择婚姻状况');
        return;
      }
      // 地址验证
      if (!this.addressList || this.addressList.length < 3) {
        this.$message.error('请选择目前居住地区');
        return;
      }
      // 详细地址
      if (!this.addData.detailedAddress) {
        this.$message.error('请输入详细家庭地址');
        return;
      }

      // 邮箱验证
      if(!this.addData.email) {
        this.$message.error('请输入邮箱');
        return;
      }
      if (this.addData.email && !/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(this.addData.email)) {
        this.$message.error('请输入正确的邮箱格式');
        return;
      }

      // 身份证号验证
      if (!this.addData.idNumber) {
        this.$message.error('请输入身份证号');
        return;
      }

      //转正日期验证
      if (this.addData.regularizationDate && this.addData.entryDate) {
        const entryDate = new Date(this.addData.entryDate);
        const regularizationDate = new Date(this.addData.regularizationDate);

        if (regularizationDate < entryDate) {
          this.$message.error('转正日期不能早于入职日期');
          return;
        }
      }
      // 新增：合同日期验证 - 不能一个为空
      const hasStartDate = !!this.addData.contractStartDate;
      const hasEndDate = !!this.addData.contractEndDate;

      if (hasStartDate !== hasEndDate) {
        this.$message.error('合同起始日期和终止日期必须同时填写或同时为空');
        return;
      }

      // 新增：如果填写了日期，则验证起始日期不能晚于终止日期
      if (hasStartDate && hasEndDate) {
        const startDate = new Date(this.addData.contractStartDate);
        const endDate = new Date(this.addData.contractEndDate);

        if (startDate > endDate) {
          this.$message.error('合同起始日期不能晚于终止日期');
          return;
        }
      }

      this.generateEmployeeId(); // 生成员工编号
      this.addData.password = this.addData.empId; // 设置默认密码
      this.calculateContractDuration(); // 计算合同年限
      const employeeData = {
        empId: this.addData.empId,
        sex: this.addData.sex,
        age: this.addData.age,
        name: this.addData.name,
        birth: this.addData.birth,
        idNumber: this.addData.idNumber,
        ethnicity: this.addData.ethnicity,
        political: this.addData.political,
        nationality: this.addData.nationality,
        address: this.addData.address,
        maritalStatus: this.addData.maritalStatus,
        detailedAddress: this.addData.detailedAddress,
        phone: this.addData.phone,
        email: this.addData.email,
        highestEducation: this.addData.highestEducation,
        entryDate: this.addData.entryDate,
        regularizationDate: this.addData.regularizationDate,
        contractStartDate: this.addData.contractStartDate,
        contractEndDate: this.addData.contractEndDate,
        contractDuration: this.addData.contractDuration,
        deptId: this.addDeptData.deptId,
        empForm: this.addData.empForm,
        password: this.addData.password,
      }
      // 调用新增员工接口
      addEmployeeAndDepartment(employeeData)
        .then((res) => {
          this.getList();
          this.$message.success("新增成功");
        })
        .catch((error) => {
          this.$message.error("新增失败：" + error.message);
        });
      this.addEmpDialogFormVisible = false;

    },
    //编辑员工信息
    editNode(row) {
      this.$nextTick(() => {
        this.editData = {
          empId: row.empId,
          sex: row.sex,
          name: row.name,
          birth: row.birth,
          age: row.age,
          ethnicity: row.ethnicity,
          idNumber: row.idNumber,
          address: row.address,
          phone: row.phone,
          email: row.email,
          maritalStatus: row.maritalStatus,
          highestEducation: row.highestEducation,
          political: row.political,
          empForm: row.empForm,
          entryDate: row.entryDate,
          regularizationDate: row.regularizationDate,
          contractStartDate: row.contractStartDate,
          contractEndDate: row.contractEndDate,
          contractDuration: row.contractDuration,
          nationality: row.nationality,
          detailedAddress: row.detailedAddress,
        }
        this.editAddressList = this.parseAreaCode(this.editData.address)
        this.editNationalityList = this.parseAreaCode(this.editData.nationality)
        this.editSex = (function(){
          const sexMap = {
            0: "女",
            1: "男"
          };
          return sexMap[row.sex];
        })();
        this.editPolitical = (function () {
          const politicalMap = {
            0: "群众",
            1: "共青团员",
            2: "中共党员",
            3: "其他"
          };
          return politicalMap[row.political];
        })();
        this.editMaritalStatus = (function () {
          const maritalStatusMap = {
            0: "未婚",
            1: "已婚"
          };
          return maritalStatusMap[row.maritalStatus];
        })();
        this.editHighestEducation = (function () {
          const educationMap = {
            0: "小学",
            1: "初中",
            2: "高中",
            3: "大专",
            4: "本科",
            5: "硕士",
            6: "博士",
            7: "其他"
          };
          return educationMap[row.highestEducation];
        })();
      })
      this.editEmpDialogFormVisible = true;
    },
    //提交编辑表单
    submitEditForm() {
      //性别验证
      if (this.editData.sex===undefined) {
        this.$message.error('请选择性别');
        return;
      }
      //员工姓名验证
      if (!this.editData.name) {
        this.$message.error('请输入员工姓名');
        return;
      }
      // 电话号码验证
      if (!this.editData.phone) {
        this.$message.error('请输入联系电话');
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(this.editData.phone)) {
        this.$message.error('请输入正确的11位手机号码');
        return;
      }
      // 邮箱验证
      if(!this.editData.email) {
        this.$message.error('请输入邮箱');
        return;
      }
      if (this.editData.email&&!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(this.editData.email)) {
        this.$message.error('请输入正确的邮箱格式');
        return;
      }
      // 身份证号验证
      if (!this.editData.idNumber) {
        this.$message.error('请输入身份证号');
        return;
      }
      // 籍贯验证
      if (!this.editNationalityList || this.editNationalityList.length < 3) {
        this.$message.error('请选择籍贯所在地');
        return;
      }
      //政治面貌验证
      if (this.editData.political===undefined) {
        this.$message.error('请选择政治面貌');
        return;
      }
      //婚姻状况验证
      if (this.editData.maritalStatus===undefined) {
        this.$message.error('请选择婚姻状况');
        return;
      }
      // 地址验证
      if (!this.editAddressList || this.editAddressList.length < 3) {
        this.$message.error('请选择目前居住地区');
        return;
      }
      // 详细地址
      if (!this.editData.detailedAddress) {
        this.$message.error('请输入详细家庭地址');
        return;
      }
      // 新增：合同日期验证 - 不能一个为空
      const hasStartDate = !!this.editData.contractStartDate;
      const hasEndDate = !!this.editData.contractEndDate;

      if (hasStartDate !== hasEndDate) {
        this.$message.error('合同起始日期和终止日期必须同时填写或同时为空');
        return;
      }

      // 新增：如果填写了日期，则验证起始日期不能晚于终止日期
      if (hasStartDate && hasEndDate) {
        const startDate = new Date(this.editData.contractStartDate);
        const endDate = new Date(this.editData.contractEndDate);

        if (startDate > endDate) {
          this.$message.error('合同起始日期不能晚于终止日期');
          return;
        }
      }
      //转正日期不能早于入职日期
      if (this.editData.regularizationDate && this.editData.entryDate) {
        const entryDate = new Date(this.editData.entryDate);
        const regularizationDate = new Date(this.editData.regularizationDate);

        if (regularizationDate < entryDate) {
          this.$message.error('转正日期不能早于入职日期');
          return;
        }
      }
      //最高学历验证
      if (this.editData.highestEducation===undefined) {
        this.$message.error('请选择最高学历');
        return;
      }
      updateEmployee(this.editData)
        .then(() => {
          this.$message.success("修改成功！");
          this.getList();
        })
        .catch((error) => {
          this.$message.error("修改失败：" + error.message);
        });
      this.editEmpDialogFormVisible = false;
    },
    //初始化编辑表单
    initEditForm() {
      this.addData = {
        empName: "",
        birth: "",
        age: "",
        sex: "",
        idNumber: "",
        ethnicity: "",
        political: "",
        nationality: "",
        address: "",
        maritalStatus: "",
        detailedAddress: "",
        phone: "",
        email: "",
        highestEducation: "",
        entryDate: "",
        contractStartDate: "",
        contractEndDate: "",
        contractDuration: "",
        empId: "",
        empForm: "",
        password: "",
      };
      this.editAddressList = [];
      this.editNationalityList = [];
      this.editSex = "";
      this.editPolitical = "";
      this.editMaritalStatus = "";
      this.editHighestEducation = "";
      this.editEmpDialogFormVisible = false;
    },
    // 格式化出生日期（编辑）
    formatEditBirthDate() {
      if (this.editData.birth) {
        this.editData.birth = this.formatDate(new Date(this.editData.birth));
      }
      this.calculateEditAge();
    },

    // 格式化入职日期（编辑）
    formatEditEntryDate() {
      if (this.editData.entryDate) {
        this.editData.entryDate = this.formatDate(new Date(this.editData.entryDate));
      }
    },

    // 格式化转正日期（编辑）
    formatEditRegularizationDate() {
      if (this.editData.regularizationDate) {
        this.editData.regularizationDate = this.formatDate(new Date(this.editData.regularizationDate));
      }
    },

    // 格式化合同起始日期（编辑）
    formatEditContractStartDate() {
      if (this.editData.contractStartDate) {
        this.editData.contractStartDate = this.formatDate(new Date(this.editData.contractStartDate));
      }
      this.calculateEditContractDuration();
    },

    // 格式化合同终止日期（编辑）
    formatEditContractEndDate() {
      if (this.editData.contractEndDate) {
        this.editData.contractEndDate = this.formatDate(new Date(this.editData.contractEndDate));
      }
      this.calculateEditContractDuration();
    },

    // 计算年龄（编辑）
    calculateEditAge() {
      if (this.editData.birth) {
        if (!this.editData.birth) return;
        const birthDate = new Date(this.editData.birth);
        const today = new Date();
        // 计算年份差
        let age = today.getFullYear() - birthDate.getFullYear();
        // 计算月份差
        const monthDiff = today.getMonth() - birthDate.getMonth();
        // 如果当前月份小于出生月份，或者月份相同但日期未到生日，年龄减1
        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
          age--;
        }
        this.editData.age = age;
      }
    },

    // 计算合同年限（编辑）
    calculateEditContractDuration() {
      if(!this.editData.contractStartDate || !this.editData.contractEndDate)
        this.editData.contractDuration = 0;
      if (this.editData.contractStartDate && this.editData.contractEndDate) {
        const startDate = new Date(this.editData.contractStartDate);
        const endDate = new Date(this.editData.contractEndDate);
        const duration = (endDate - startDate) / (1000 * 60 * 60 * 24 * 365);
        this.editData.contractDuration = Math.round(duration);
      }
    },

    // 格式化籍贯（编辑）
    formatEditNationality() {
      if (this.editNationalityList && this.editNationalityList.length === 3) {
        const [provinceCode, cityCode, districtCode] = this.editNationalityList;
        const province = this.findAreaName(provinceCode);
        const city = this.findAreaName(cityCode);
        const district = this.findAreaName(districtCode);
        this.editData.nationality = `${province}/${city}/${district}`;
      }
    },

    // 格式化地址（编辑）
    formatEditAddress() {
      if (this.editAddressList && this.editAddressList.length === 3) {
        const [provinceCode, cityCode, districtCode] = this.editAddressList;
        const province = this.findAreaName(provinceCode);
        const city = this.findAreaName(cityCode);
        const district = this.findAreaName(districtCode);
        this.editData.address = `${province}/${city}/${district}`;
      }
    },
    // 解析地区代码
    parseAreaCode(address) {
      if (!address) return [];

      // 按 / 分割省、市、区
      const [provinceName, cityName, districtName] = address.split('/');

      // 查找省代码
      const provinceCode = this.findCodeByName(provinceName, this.regionData);
      if (!provinceCode) return []; // 如果找不到省，直接返回空数组

      // 查找市代码
      const provinceData = this.findAreaByCode(provinceCode, this.regionData);
      const cityCode = this.findCodeByName(cityName, provinceData.children || []);
      if (!cityCode) return [provinceCode]; // 如果找不到市，返回省代码

      // 查找区代码
      const cityData = this.findAreaByCode(cityCode, provinceData.children || []);
      const districtCode = this.findCodeByName(districtName, cityData.children || []);

      return [provinceCode, cityCode, districtCode];
    },
    // 更新最高学历
    updateHighestEducation(value) {
      this.editData.highestEducation = value;
    },
    // 更新性别
    updateSex(value) {
      this.editData.sex = value;
    },
    // 更新政治面貌
    updatePolitical(value) {
      this.editData.political = value;
    },
    // 更新婚姻状况
    updateMaritalStatus(value) {
      this.editData.maritalStatus = value;
    },
    // 根据名称查找代码
    findCodeByName(name, options) {
      for (const option of options) {
        if (option.label === name) {
          return option.value;
        }
        if (option.children) {
          const result = this.findCodeByName(name, option.children);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },
    //重置选中员工密码
    resetPassword(empId, name) {
      ElMessageBox.confirm(`确定要重置员工 ${empId}（${name}）的密码吗？重置后密码将设置为员工编号。`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 调用重置密码接口
          resetEmployeePassword({ empId }).then(() => {
            ElMessage.success('密码重置成功');
            this.getList();
          }).catch(() => {
            ElMessage.error('密码重置失败');
          });
        })
        .catch(() => {
          ElMessage.info('已取消密码重置');
        });
    },
    //批量删除员工
    onDelete() {
      console.log(this.delEmpId);
      if (this.delEmpId.length > 0) {
        ElMessageBox.confirm(`确定要删除选中的 ${this.delEmpId.length} 条记录吗？`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            // 调用批量删除接口
            const empIds = this.delEmpId.join(',');
            deleteBatchEmployee({ empIds }).then(() => {
              ElMessage.success('删除成功');
              this.getList()
            }).catch(() => {
              ElMessage.error('删除失败');
            })
          })
          .catch(() => {
            ElMessage.info('已取消删除');
          });
      } else {
        ElMessage.warning('请先选中要删除的员工');
      }
    },
    //删除选中的员工
    del(empId, name) {
      ElMessageBox.confirm(`确定要删除员工 ${empId}（${name}）吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 调用删除接口
          deleteEmployee({ empId }).then(() => {
            ElMessage.success('删除成功');
            this.getList()
          }).catch(() => {
            ElMessage.error('删除失败');
          });
        })
        .catch(() => {
          ElMessage.info('已取消删除');
        });
    },
    //当页码发生改变时执行函数
    handlerCurrentPage(number) {
      this.formData.pageNum = number;
      this.page.currentPage = number;
      this.getList();
    },
    //点击选中复选框
    handleSelectionChange(selection) {
      this.delEmpId = [];
      for (let index in selection) {
        this.delEmpId.push(selection[index].empId);
      }
      console.log(this.delEmpId);
    },
    //API-获取分页数据
    getList() {
      this.formData.pageSize = this.page.pageSize
      getEmployeeList(this.formData).then((res) => {
        this.nodeList = res.result.records;
        this.page.total = res.result.total;
        this.page.currentPage = res.result.current;
      });
    },
    //API-获取所有部门
    getDepts(){
      getAllDepts().then((res) => {
        for (let index in res.result) {
          let obj = {}
          obj.label = res.result[index].name
          obj.value = res.result[index].id
          this.deptList.push(obj)
        }
      });
    }
  },
};
</script>

<style scoped>
.employee-container {
  padding: 20px;
  height: 95%;
  display: flex;
  flex-direction: column;
}

.search-form {
  background: #fff;
  padding: 20px 20px 0 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.employee-table {
  flex: 1;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination {
  text-align: right;
  background: #fff;
  padding: 10px 20px;
  border-radius: 4px;
}

/* 表格样式调整 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--border th) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table--border td) {
  border-right: 1px solid #ebeef5;
}

/* 按钮样式调整 */
:deep(.el-button--small) {
  padding: 5px 10px;
  font-size: 12px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.demo-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-row :deep(.el-form-item) {
  flex: 1;
}

.demo-form .el-input {
  --el-input-width: 220px;
}

.demo-form .el-select {
  --el-select-width: 220px;
}
</style>